/**
 * 用户管理模块
 */
const router = require('koa-router')()
const AutoNavi = require('./../models/AutoNavi')
const util = require('./../utils/util')
router.prefix('/AutoNavi')
// 用户列表
router.get('/list', async (ctx) => {
  const { userId, userName, state } = ctx.request.query;
  const { page, skipIndex } = util.pager(ctx.request.query)
  let params = {}
  if (userId) params.userId = userId;
  if (userName) params.userName = userName;
  if (state && state != '0') params.state = state;
  try {
    // 根据条件查询所有用户列表
    const query = AutoNavi.find(params)
    const list = await query.skip(skipIndex).limit(page.pageSize)
    const total = await AutoNavi.countDocuments(params);
    ctx.body = util.success({
      page: {
        ...page,
        total
      },
      list
    })
  } catch (error) {
    ctx.body = util.fail(`查询异常:${error.stack}`)
  }
})

// 删除接口
router.get('/delete', async (ctx) => {
  // 待删除的用户Id数组
  const { ids } = ctx.request.query
  console.log(ids, 'idsids')
  const res = await AutoNavi.findByIdAndRemove(ids)

  // const res = await AutoNavi.deleteMany({ _id: { $all: [ids] } })
  console.log(res)
  if (res) {
    ctx.body = util.success(`共删除成功`)
    return;
  }
  ctx.body = util.fail('删除失败');
})
// 新增接口
router.post('/operate', async (ctx) => {
  console.log(ctx.request.query, 'ctx.request.query;ctx.request.query;ctx.request.query;')
  const { address, postionmodel, temporary } = ctx.request.body;
  if (!address || !postionmodel || !temporary) {
    ctx.body = util.fail('参数错误', util.CODE.PARAM_ERROR)
    return;
  }
  try {
    const AutoNavia = new AutoNavi({
      address,
      postionmodel,
      temporary,
    })
    AutoNavia.save();
    ctx.body = util.success('', '坐标新增成功');
  } catch (error) {
    ctx.body = util.fail(error.stack, '坐标新增失败');
  }
})
// 编辑接口
router.post('/editoperate', async (ctx) => {
  const { _id, address, postionmodel, temporary } = ctx.request.body;
  if (!address || !postionmodel || !temporary) {
    ctx.body = util.fail('参数错误', util.CODE.PARAM_ERROR)
    return;
  }
  try {
    let params = {
      address, postionmodel, temporary
    }
    await AutoNavi.findByIdAndUpdate(_id, params)
    ctx.body = util.success('', '坐标修改成功');
  } catch (error) {
    ctx.body = util.fail(error.stack, '坐标修改失败');
  }

})
module.exports = router
